package com.xiaoxiang.cameracontrol;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraCaptureSession;
import android.hardware.camera2.CameraCharacteristics;
import android.hardware.camera2.CameraDevice;
import android.hardware.camera2.CameraManager;
import android.hardware.camera2.CaptureRequest;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_CODE_TAKE_VIDEO = 2;
    private static final int REQUEST_PERMISSIONS_CODE = 1;
    private static final String FILE_PATH = "/sdcard/sysvideocamera.3gp";

    private static final String[] REQUIRED_PERMISSIONS = {
            Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    private Button start_btn;
    private Button stop_btn;
    private TextView record_state;
    private SurfaceView my_surface_view;

    private CameraDevice my_camera;

    private Handler mHandler;
    private Handler mainHandler;

    private CaptureRequest.Builder mPreviewBuilder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        builder.detectFileUriExposure();

        this.start_btn = findViewById(R.id.start_btn);
        this.stop_btn = findViewById(R.id.stop_btn);
        this.record_state = findViewById(R.id.record_state);
        this.my_surface_view = findViewById(R.id.my_surface_view);

        //this.initSurfaceView();

        this.start_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
                intent.setAction("android.media.action.VIDEO_CAPTURE");
                File file = new File(FILE_PATH);
                if(file.exists()){
                    file.delete();
                }
                Uri uri = Uri.fromFile(file);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
            }
        });


    }

    private void initSurfaceView() {
        SurfaceHolder holder = this.my_surface_view.getHolder();
        holder.addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(@NonNull SurfaceHolder surfaceHolder) {
                initCameraAndPreview();
            }

            @Override
            public void surfaceChanged(@NonNull SurfaceHolder surfaceHolder, int i, int i1, int i2) {

            }

            @Override
            public void surfaceDestroyed(@NonNull SurfaceHolder surfaceHolder) {
                if (my_camera != null) {
                    my_camera.close();
                    my_camera = null;
                }
            }
        });
    }


    private void initCameraAndPreview() {
        HandlerThread handlerThread = new HandlerThread("my camera");
        handlerThread.start();
        mHandler = new Handler(handlerThread.getLooper());
        mainHandler = new Handler(getMainLooper());
        try {
            String camera_id = "" + CameraCharacteristics.LENS_FACING_BACK;
            CameraManager mCManager = (CameraManager) this.getSystemService(Context.CAMERA_SERVICE);
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "打开相机失败", Toast.LENGTH_SHORT).show();
                return;
            }
            mCManager.openCamera(camera_id, deviceStateCallback, mHandler);
        }catch (CameraAccessException e){
            Toast.makeText(this, "打开相机失败", Toast.LENGTH_SHORT).show();
        }
    }

    private CameraDevice.StateCallback deviceStateCallback = new CameraDevice.StateCallback() {
        @Override
        public void onOpened(@NonNull CameraDevice cameraDevice) {
            my_camera = cameraDevice;
            try{
                takePreview();
            }catch (CameraAccessException e){
                e.printStackTrace();
            }
        }

        @Override
        public void onDisconnected(@NonNull CameraDevice cameraDevice) {
            if(my_camera != null){
                my_camera.close();
                my_camera = null;
            }
        }

        @Override
        public void onError(@NonNull CameraDevice cameraDevice, int i) {

        }
    };

    public void takePreview() throws CameraAccessException{
        SurfaceHolder holder = my_surface_view.getHolder();
        mPreviewBuilder = my_camera.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
        mPreviewBuilder.addTarget(holder.getSurface());
        my_camera.createCaptureSession(Arrays.asList(holder.getSurface()),
                mSessionPreviewStateCallback, mHandler);

    }

    private CameraCaptureSession.StateCallback mSessionPreviewStateCallback = new CameraCaptureSession.StateCallback() {
        @Override
        public void onConfigured(@NonNull CameraCaptureSession cameraCaptureSession) {

        }

        @Override
        public void onConfigureFailed(@NonNull CameraCaptureSession cameraCaptureSession) {
            System.out.println("摄像头配置失败");
        }


    };

    private void takePicture(){

    }

    @Override
    public void onResume(){
        super.onResume();
        if (!isRequiredPermissionsGranted() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            requestPermissions(REQUIRED_PERMISSIONS, REQUEST_PERMISSIONS_CODE);
        }
    }

    /**
     * 判断我们需要的权限是否被授予，只要有一个没有授权，我们都会返回 false。
     *
     * @return true 权限都被授权
     */
    private boolean isRequiredPermissionsGranted() {
        for (String permission : REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(this, permission) == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.i("camera", "拍摄完成");
        if(requestCode==REQUEST_CODE_TAKE_VIDEO && resultCode==RESULT_OK){
            Uri uriVideo = data.getData();
            Cursor cursor = this.getContentResolver().query(uriVideo, null, null, null, null);
            if(cursor.moveToNext()){
                cursor.getColumnIndex("_data");
                int index = cursor.getColumnIndex("_data");
                String path = cursor.getString(index);
                Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
            }
        }


        super.onActivityResult(requestCode, resultCode, data);
    }
}